﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AMatysiak.Methods
{
    public static class TypeExtensions
    {
        public static double ToDouble(this string s)
        {
            s = s.NormalizeCurrencyValue();
            return ConvertStringToDouble(s);
        }

        internal static string NormalizeCurrencyValue(this string s)
        {
            if (s.IsEmpty())
                return "0";
            if (s.Contains('.'))
                s = s.Replace('.', ',');
            if (s.Contains(" zł"))
                s = s.Replace(" zł", "");
            return s;
        }

        private static double ConvertStringToDouble(string s)
        {
            return Math.Round(double.Parse(s), 2, MidpointRounding.AwayFromZero);
        }

        public static string ToCurrency(this string s)
        {
            double d = s.ToDouble();
            return d.ToString("C2");
        }

        public static int ToInt(this string s)
        {
            if (s.IsEmpty())
                return 0;

            return int.Parse(s);
        }

        public static DateTime ToDate(this string s)
        {
            return DateTime.Parse(s).Date;
        }

        public static string ToShortDate(this string s)
        {
            return DateTime.Parse(s).ToShortDateString();
        }

        public static bool ToBool(this string s)
        {
            if (s.ToLower() == "true" || s == "1" || s.ToLower() == "checked")
                return true;
            else if (s.ToLower() == "false" || s == "0" || s.ToLower() == "unchecked")
                return false;
            else
                return bool.Parse(s);
        }

        public static bool Equality(this Array a, Array b)
        {
            if (a.GetType() != b.GetType())
                return false;

            if (a.Length != b.Length)
                return false;

            for (int i = 0; i < a.Length; i++)
            {
                object ai = a.GetValue(i);
                object bi = b.GetValue(i);
                if (!object.Equals(ai, bi))
                    return false;
            }

            return true;
        }
    }
}
